<?php

class PlayerController {

    public static function admin() {
        rpc::_add_response('result', 'ok');
        $x = rpc::_get_value('x',0);
        $y = rpc::_get_value('y',0);
        $id = Map::getIdByXY($x, $y);
        rpc::_add_response('id', $id);

        $method = rpc::_get_value('submethod',0);
        switch ($method)
        {
            case 'set_tile':
                $ground_type = rpc::_get_value('ground_type', 0);
                $water_type = rpc::_get_value('water_type', 0);
                Map::initTile($id,$x,$y,$ground_type,$water_type);
                break;
            case 'getTilesInfo':
                $res = Map::getTilesInfo(rpc::_get_value('tiles'));
                rpc::_add_response('tiles', $res);
                break;
        }
    }
    public static function init() {
        $player = new Player(rpc::$user_id);
        $data = $player->is_registered();
        if ($data) {
            $registered = true;
            // already registered
        } else {
            //not registered yet
            $registered = false;
            $data = $player->create();
        }

        $player->setProperty('lastLogin', rpc::$time);
        $player->setProperty('first_name', rpc::_get_value('first_name', ''));
        $player->setProperty('last_name', rpc::_get_value('last_name', ''));
        $player->setProperty('sex', rpc::_get_value('sex', 0));
        $bdate = rpc::_get_value('age', 0);

        if ($bdate) {
            $normal = explode('.', $bdate);
            if (count($normal) == 2) {
                $age = 0; // только дата рождения
            } else //17.8.1988 // 2011-01-19 16:22:30 {
            $age = time() - (int) strtotime($normal[2] . '-' . $normal[1] . '-' . $normal[0]);
            $age = floor($age / 31536000);
        }

        $player->setProperty('age', $age);

        // setting friends
        $friends_string = rpc::_get_value('friends', '');
        $player->saveFriendsString($friends_string);
        // foreach friends return their profiles
        $friendProfiles = $player->getFriendProfiles();

        function cmp($a, $b) {
            return $a['exp'] - $b['exp'];
        }


        uasort($friendProfiles, 'cmp');
        $out_friends = null;

        foreach ($friendProfiles as $id => $value) {
            $out_friends['u' . $id] = $value; // chrome, you are fucking piece of shit!
        }

        rpc::_add_response('friends', $out_friends);


        $profile = $player->getProfileClean();

        $dailyBonus = PlayerController::getDailyBonus($player, $registered);
        if (is_array($dailyBonus) && count($dailyBonus)) {
            if (isset($dailyBonus['money']))
            $player->addMoney($dailyBonus['money']);
            rpc::_add_response('dailyBonus', $dailyBonus);
        }


        $player->save();
        $profile = $player->getProfileClean();
        rpc::_add_response('profile', $profile);

        // controllers
        // recipes
        //$recipes = $player->RecipesController->getAll();
        //rpc::_add_response('recipes',$recipes);
        // plants
        //$plants = $player->PlantsController->getAll();
        //rpc::_add_response('plants',$plants);
        // inventory
        //$inventory = $player->InventoryController->getAll();
        //rpc::_add_response('inventory',$inventory);
    }

    public static function visitFriend() {
        $friend_id = rpc::_get_value('friend_id', '');
        if (!is_numeric($friend_id)) {
            rpc::_add_response('error', '$friend_id');
            return false;
        }
        rpc::_add_response('uid', $friend_id);
        // ВОЗВРАЩАЕМ ИНФУ О ДРУГЕ И ЕГО ДОМЕ
        $friend = new Friend($friend_id);
        if(!$friend->is_registered())
        {
            rpc::_add_response('error', 'not_registered');
            return false;
        }
        if (!$friend->isFriend(rpc::$user_id)) {
            // то не друг!
            rpc::_add_response('error', 'not_in_friend_list');
            return false;
        }
        // ЕЖЕДНЕВНЫЙ БОНУС
        // проверяем, посещал ли друга сегодня?
        $query = 'SELECT COUNT(1) as cnt FROM `players_friendbonus` WHERE `user_id`=' . rpc::$user_id . ' AND `friend_id`=' . $friend_id;
        $result = _database::torow($query);


        if ($result && isset($result['cnt']) && $result['cnt'] == 0) { // если нет, выдаем бонус
            $bonus = PlayerController::getFriendBonus(rpc::$user_id, $friend_id);
            if ($bonus) {
                $query = 'INSERT INTO `players_friendbonus` SET `user_id`=' . rpc::$user_id . ' , `friend_id`=' . $friend_id . ' ON DUPLICATE KEY UPDATE `user_id`=' . rpc::$user_id . ' ,`friend_id`=' . $friend_id;
                _database::query($query);
                $player = new Player(rpc::$user_id);
                $player->getProfile();

                if ($bonus['money']) {
                    $player->addMoney($bonus['money']);
                }

                $sex_choice = $player->data['sex'] == 1 ? 'посетила' : 'посетил';
                $sex_choice_2 = $player->data['sex'] == 1 ? 'забрала' : 'забрал';
                $sex_choice_3 = $friend->data['sex'] == 1 ? 'отложила' : 'отложил';

                $text = 'твою норку и '.$sex_choice_2.' немного денег, которые ты '.$sex_choice_3.' для друзей..';
                $r = Notify::pend($friend_id, $player->data['first_name'].' '.$player->data['last_name'].' '.$sex_choice.' '.$text);

                $player->save();
            }
            rpc::_add_response('bonus', $bonus);
        }
        Statistic::add('friendvisit_30', 1);
        return true;
    }

    public static function getFriendBonus($uid, $fid) {
        $bonus = array('money' => 10);
        return $bonus;
    }

    public static function getDailyBonus($player, $registered) {
        if (!$registered)
        return array();

        $minNoGamePeriod = _settings::$game_settings['bonus_period'];
        $maxNoGamePeriod = 2 * $minNoGamePeriod;
        $moneyBase = _settings::$game_settings['bonus_money_base'];

        $bonusMult = (int)$player->data['lastBonusDay'];
        log::debug('lastBonusDay',$bonusMult);

        $lastBonusGet = $player->data["lastGetBonus"]; // when got bonus
        log::debug('lastBonusGet', date('Y-m-d H:i',$lastBonusGet));
        $lastSave = $player->data["lastSave"]; // when login last time
        log::debug('lastSave', date('Y-m-d H:i',$lastSave));
        // and last get bonus was more then 24h
        // and lastSave was less then 48h ago
        if (!$lastBonusGet || (((rpc::$time - $lastBonusGet) > $minNoGamePeriod) && ((rpc::$time - $lastSave) < $maxNoGamePeriod))) {
            log::debug('>24 LGB <48 LS');
            $player->setProperty('lastGetBonus', rpc::$time);
            $player->setProperty('lastBonusDay', min(_settings::$game_settings['bonus_max_days'], $bonusMult + 1));
            log::debug( min(_settings::$game_settings['bonus_max_days'], $bonusMult + 1),'setting bonus days:');
            $money = ($bonusMult + 1) * $moneyBase;
            $bonus = array('money' => $money, 'lastBonusDay' => $bonusMult + 1);
            return $bonus;
            // else if last get bonus was more then 24h
            // and lastSave was more then 48h ago
        } else if (((rpc::$time - $lastBonusGet) > $minNoGamePeriod) && ((rpc::$time - $lastSave) >= $maxNoGamePeriod)) {
            log::debug('>24 LGB >=48 LS');
            $bonusMult = 0;
            $player->setProperty('lastGetBonus', rpc::$time);
            $player->setProperty('lastBonusDay', 1);
            $money = $moneyBase;
            $bonus = array('money' => $money, 'lastBonusDay' => $bonusMult + 1);
            return $bonus;
        }
        else
        {
            log::debug('<24 LGB >=48 LS');
        }
        return array();
    }

    public static function plant() {
        $tile_id = rpc::_get_value('tile_id', 0);
        $plant_id = rpc::_get_value('plant_id', 0);
        $cost = rpc::_get_value('cost', 0);

        if(!$tile_id || !$plant_id || !$cost)
        {
            rpc::_add_response('error', 'params');
            return false;
        }
        $player = new Player(rpc::$user_id);
        $data = $player->is_registered();
        if(!$data)
        {
            rpc::_add_response('error', 'registered');
            return false;
        }

        $result = $player->PlantsController->plant($tile_id,$plant_id);
        if($result)
        {
            $player->PlantsController->save();
            rpc::_add_response('planted', 1);
        }
    }

}

?>
